{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "GLUE_Benchmark.ipynb",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU",
    "pycharm": {
      "stem_cell": {
        "cell_type": "raw",
        "source": [],
        "metadata": {
          "collapsed": false
        }
      }
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "metadata": {
        "id": "o_0K1lsW1dj9",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell\n",
        "\n",
        "# install NeMo\n",
        "BRANCH = 'main'\n!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "pycharm": {
          "name": "#%%\n"
        },
        "id": "JFWG-jYCfvD7",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:\n",
        "# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'\n",
        "\n",
        "! pip install ipywidgets\n",
        "! jupyter nbextension enable --py widgetsnbextension\n",
        "\n",
        "# Please restart the kernel after running this cell"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "dzqD2WDFOIN-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "from nemo.collections import nlp as nemo_nlp\n",
        "from nemo.utils.exp_manager import exp_manager\n",
        "\n",
        "import os\n",
        "import wget \n",
        "import torch\n",
        "import pytorch_lightning as pl\n",
        "from omegaconf import OmegaConf"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "daYw_Xll2ZR9",
        "colab_type": "text"
      },
      "source": [
        "In this tutorial, we are going to describe how to finetune a BERT-like model based on [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) on [GLUE: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding](https://openreview.net/pdf?id=rJ4km2R5t7). \n",
        "\n",
        "# GLUE tasks\n",
        "GLUE Benchmark includes 9 natural language understanding tasks:\n",
        "\n",
        "## Single-Sentence Tasks\n",
        "\n",
        "* CoLA - [The Corpus of Linguistic Acceptability](https://arxiv.org/abs/1805.12471) is a set of English sentences from published linguistics literature. The task is to predict whether a given sentence is grammatically correct or not.\n",
        "* SST-2 - [The Stanford Sentiment Treebank](https://nlp.stanford.edu/~socherr/EMNLP2013_RNTN.pdf) consists of sentences from movie reviews and human annotations of their sentiment. The task is to predict the sentiment of a given sentence: positive or negative.\n",
        "\n",
        "## Similarity and Paraphrase tasks\n",
        "\n",
        "* MRPC - [The Microsoft Research Paraphrase Corpus](https://www.aclweb.org/anthology/I05-5002.pdf) is a corpus of sentence pairs automatically extracted from online news sources, with human annotations for whether the sentences in the pair are semantically equivalent.\n",
        "* QQP - [The Quora Question Pairs](https://www.quora.com/q/quoradata/First-Quora-Dataset-Release-Question-Pairs) dataset is a collection of question pairs from the community question-answering website Quora. The task is to determine whether a pair of questions are semantically equivalent.\n",
        "* STS-B - [The Semantic Textual Similarity Benchmark](https://arxiv.org/abs/1708.00055) is a collection of sentence pairs drawn from news headlines, video, and image captions, and natural language inference data. The task is to determine how similar two sentences are.\n",
        "\n",
        "## Inference Tasks\n",
        "\n",
        "* MNLI - [The Multi-Genre Natural Language Inference Corpus](https://cims.nyu.edu/~sbowman/multinli/multinli_0.9.pdf) is a crowdsourced collection of sentence pairs with textual entailment annotations. Given a premise sentence and a hypothesis sentence, the task is to predict whether the premise entails the hypothesis (entailment), contradicts the hypothesis (contradiction), or neither (neutral). The task has the matched (in-domain) and mismatched (cross-domain) sections.\n",
        "* QNLI - [The Stanford Question Answering Dataset](https://nlp.stanford.edu/pubs/rajpurkar2016squad.pdf) is a question-answering dataset consisting of question-paragraph pairs, where one of the sentences in the paragraph (drawn from Wikipedia) contains the answer to the corresponding question. The task is to determine whether the context sentence contains the answer to the question.\n",
        "* RTE The Recognizing Textual Entailment (RTE) datasets come from a series of annual [textual entailment challenges](https://aclweb.org/aclwiki/Recognizing_Textual_Entailment). The task is to determine whether the second sentence is the entailment of the first one or not.\n",
        "* WNLI - The Winograd Schema Challenge is a reading comprehension task in which a system must read a sentence with a pronoun and select the referent of that pronoun from a list of choices (Hector Levesque, Ernest Davis, and Leora Morgenstern. The winograd schema challenge. In Thirteenth International Conference on the Principles of Knowledge Representation and Reasoning. 2012).\n",
        "\n",
        "All tasks are classification tasks, except for the STS-B task which is a regression task. All classification tasks are 2-class problems, except for the MNLI task which has 3-classes.\n",
        "\n",
        "More details about GLUE benchmark could be found [here](https://gluebenchmark.com/)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZnuziSwJ1yEB",
        "colab_type": "text"
      },
      "source": [
        "# Datasets\n",
        "\n",
        "**To proceed further, you need to download the GLUE data.** For example, you can download [this script](https://gist.githubusercontent.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e/raw/17b8dd0d724281ed7c3b2aeeda662b92809aadd5/download_glue_data.py) using `wget` and then execute it by running:\n",
        "\n",
        "`python download_glue_data.py`\n",
        "\n",
        "use `--tasks TASK` if datasets for only selected GLUE tasks are needed\n",
        "\n",
        "After running the above commands, you will have a folder `glue_data` with data folders for every GLUE task. For example, data for MRPC task would be under glue_data/MRPC.\n",
        "\n",
        "This tutorial and [examples/nlp/glue_benchmark/glue_benchmark.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/glue_benchmark/glue_benchmark.py) work with all GLUE tasks without any modifications. For this tutorial, we are going to use MRPC task.\n",
        "\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "--wJ2891aIIE",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# supported task names: [\"cola\", \"sst-2\", \"mrpc\", \"sts-b\", \"qqp\", \"mnli\", \"qnli\", \"rte\", \"wnli\"]\n",
        "TASK = 'mrpc'\n",
        "DATA_DIR = 'glue_data/MRPC'\n",
        "WORK_DIR = \"WORK_DIR\"\n",
        "MODEL_CONFIG = 'glue_benchmark_config.yaml'"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qB0oLE4R9EhJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "! ls -l $DATA_DIR"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gMWuU69pbUDe",
        "colab_type": "text"
      },
      "source": [
        "For each task, there are 3 files: `train.tsv, dev.tsv, and test.tsv`. Note, MNLI has 2 dev sets: matched and mismatched, evaluation on both dev sets will be done automatically."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6UDPgadLN6SG",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's take a look at the training data \n",
        "! head -n 5 {DATA_DIR}/train.tsv"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_whKCxfTMo6Y",
        "colab_type": "text"
      },
      "source": [
        "# Model configuration\n",
        "\n",
        "Now, let's take a closer look at the model's configuration and learn to train the model.\n",
        "\n",
        "GLUE model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model followed by a Sequence Regression module (for STS-B task) or  Sequence classifier module (for the rest of the tasks).\n",
        "\n",
        "The model is defined in a config file which declares multiple important sections. They are:\n",
        "- **model**: All arguments that are related to the Model - language model, a classifier, optimizer and schedulers, datasets and any other related information\n",
        "\n",
        "- **trainer**: Any argument to be passed to PyTorch Lightning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "T1gA8PsJ13MJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# download the model's configuration file \n",
        "config_dir = WORK_DIR + '/configs/'\n",
        "os.makedirs(config_dir, exist_ok=True)\n",
        "if not os.path.exists(config_dir + MODEL_CONFIG):\n",
        "    print('Downloading config file...')\n",
        "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/glue_benchmark/' + MODEL_CONFIG, config_dir)\n",
        "else:\n",
        "    print ('config file is already exists')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mX3KmWMvSUQw",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# this line will print the entire config of the model\n",
        "config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\n",
        "print(config_path)\n",
        "config = OmegaConf.load(config_path)\n",
        "print(OmegaConf.to_yaml(config))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZCgWzNBkaQLZ",
        "colab_type": "text"
      },
      "source": [
        "# Model Training\n",
        "## Setting up Data within the config\n",
        "\n",
        "Among other things, the config file contains dictionaries called **dataset**, **train_ds** and **validation_ds**. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
        "\n",
        "We assume that both training and evaluation files are located in the same directory, and use the default names mentioned during the data download step. \n",
        "So, to start model training, we simply need to specify `model.dataset.data_dir`, like we are going to do below.\n",
        "\n",
        "Also notice that some config lines, including `model.dataset.data_dir`, have `???` in place of paths, this means that values for these fields are required to be specified by the user.\n",
        "\n",
        "Let's now add the data directory path, task name and output directory for saving predictions to the config."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LQHCJN-ZaoLp",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "config.model.task_name = TASK\n",
        "config.model.output_dir = WORK_DIR\n",
        "config.model.dataset.data_dir = DATA_DIR"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nB96-3sTc3yk",
        "colab_type": "text"
      },
      "source": [
        "## Building the PyTorch Lightning Trainer\n",
        "\n",
        "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem.\n",
        "\n",
        "Let's first instantiate a Trainer object"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1tG4FzZ4Ui60",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "print(\"Trainer config - \\n\")\n",
        "print(OmegaConf.to_yaml(config.trainer))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "knF6QeQQdMrH",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# lets modify some trainer configs\n",
        "# checks if we have GPU available and uses it\n",
        "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
        "config.trainer.devices = 1\n",
        "config.trainer.accelerator = accelerator\n",
        "\n",
        "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
        "\n",
        "# for mixed precision training, uncomment the line below (precision should be set to 16 and amp_level to O1):\n",
        "# config.trainer.amp_level = O1\n",
        "\n",
        "# remove distributed training flags\n",
        "config.trainer.strategy = None\n",
        "\n",
        "# setup max number of steps to reduce training time for demonstration purposes of this tutorial\n",
        "config.trainer.max_steps = 128\n",
        "\n",
        "trainer = pl.Trainer(**config.trainer)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8IlEMdVxdr6p",
        "colab_type": "text"
      },
      "source": [
        "## Setting up a NeMo Experiment\n",
        "\n",
        "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8uztqGAmdrYt",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
        "\n",
        "# the exp_dir provides a path to the current experiment for easy access\n",
        "exp_dir = str(exp_dir)\n",
        "exp_dir"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8tjLhUvL_o7_",
        "colab_type": "text"
      },
      "source": [
        "Before initializing the model, we might want to modify some of the model configs. For example, we might want to modify the pretrained BERT model and use [Megatron-LM BERT](https://arxiv.org/abs/1909.08053) or [AlBERT model](https://arxiv.org/abs/1909.11942):"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Xeuc2i7Y_nP5",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# get the list of supported BERT-like models, for the complete list of HugginFace models, see https://huggingface.co/models\n",
        "print(nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True))\n",
        "\n",
        "# specify BERT-like model, you want to use, for example, \"megatron-bert-345m-uncased\" or 'bert-base-uncased'\n",
        "PRETRAINED_BERT_MODEL = \"albert-base-v1\""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RK2xglXyAUOO",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# add the specified above model parameters to the config\n",
        "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fzNZNAVRjDD-",
        "colab_type": "text"
      },
      "source": [
        "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.\n",
        "Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NgsGLydWo-6-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "model = nemo_nlp.models.GLUEModel(cfg=config.model, trainer=trainer)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kQ592Tx4pzyB",
        "colab_type": "text"
      },
      "source": [
        "## Monitoring training progress\n",
        "Optionally, you can create a Tensorboard visualization to monitor training progress."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mTJr16_pp0aS",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  from google import colab\n",
        "  COLAB_ENV = True\n",
        "except (ImportError, ModuleNotFoundError):\n",
        "  COLAB_ENV = False\n",
        "\n",
        "# Load the TensorBoard notebook extension\n",
        "if COLAB_ENV:\n",
        "  %load_ext tensorboard\n",
        "  %tensorboard --logdir {exp_dir}\n",
        "else:\n",
        "  print(\"To use tensorboard, please use this notebook in a Google Colab environment.\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CFgAlaIdndjW",
        "colab_type": "text"
      },
      "source": [
        "Note, it’s recommended to finetune the model on each task separately. Also, based on [GLUE Benchmark FAQ#12](https://gluebenchmark.com/faq), there are might be some differences in dev/test distributions for QQP task and in train/dev for WNLI task."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hUvnSpyjp0Dh",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# start model training\n",
        "trainer.fit(model)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ref1qSonGNhP",
        "colab_type": "text"
      },
      "source": [
        "## Training Script\n",
        "\n",
        "If you have NeMo installed locally, you can also train the model with [examples/nlp/glue_benchmark/glue_benchmark.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/glue_benchmark/glue_benchmark.py).\n",
        "\n",
        "To run training script, use:\n",
        "\n",
        "`python glue_benchmark.py \\\n",
        " model.dataset.data_dir=PATH_TO_DATA_DIR \\\n",
        " model.task_name=TASK`\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KVPFofXaoKNE",
        "colab_type": "text"
      },
      "source": [
        "Average results after 3 runs:\n",
        "\n",
        "| Task  |         Metric           | ALBERT-large | ALBERT-xlarge | Megatron-345m | BERT base paper | BERT large paper |\n",
        "|-------|--------------------------|--------------|---------------|---------------|-----------------|------------------|\n",
        "| CoLA  | Matthew's correlation    |     54.94    |     61.72     |     64.56     |      52.1       |       60.5       |\n",
        "| SST-2 | Accuracy                 |     92.74    |     91.86     |     95.87     |      93.5       |       94.9       |\n",
        "| MRPC  | F1/Accuracy              |  92.05/88.97 |  91.87/88.61  |  92.36/89.46  |      88.9/-     |     89.3/-       |\n",
        "| STS-B | Person/Spearman corr.    |  90.41/90.21 |  90.07/90.10  |  91.51/91.61  |     -/85.8      |      -/86.5      |\n",
        "| QQP   | F1/Accuracy              |  88.26/91.26 |  88.80/91.65  |  89.18/91.91  |     71.2/-      |     72.1/-       |\n",
        "| MNLI  | Matched /Mismatched acc. |  86.69/86.81 |  88.66/88.73  |  89.86/89.81  |    84.6/83.4    |     86.7/85.9    |\n",
        "| QNLI  | Accuracy                 |     92.68    |     93.66     |     94.33     |      90.5       |       92.7       |\n",
        "| RTE   | Accuracy                 |     80.87    |     82.86     |     83.39     |      66.4       |       70.1       |\n",
        "\n",
        "WNLI task was excluded from the experiments due to the problematic WNLI set.\n",
        "The dev sets were used for evaluation for ALBERT and Megatron models, and the test sets results for [the BERT paper](https://arxiv.org/abs/1810.04805).\n",
        "\n",
        "Hyperparameters used to get the results from the above table, could be found in the table below. Some tasks could be further finetuned to improve performance numbers, the tables are for a baseline reference only.\n",
        "Each cell in the table represents the following parameters:\n",
        "Number of GPUs used/ Batch Size/ Learning Rate/ Number of Epochs. For not specified parameters, please refer to the default parameters in the training script.\n",
        "\n",
        "| Task  | ALBERT-large | ALBERT-xlarge | Megatron-345m |\n",
        "|-------|--------------|---------------|---------------|\n",
        "| CoLA  | 1 / 32 / 1e-5 / 3  |  1 / 32 / 1e-5 / 10 |  4 / 16 / 2e-5 / 12 |\n",
        "| SST-2 | 4 / 16 / 2e-5 / 5  |  4 / 16 / 2e-5 /12  |  4 / 16 / 2e-5 / 12 |\n",
        "| MRPC  | 1 / 32 / 1e-5 / 5  |  1 / 16 / 2e-5 / 5  |  1 / 16 / 2e-5 / 10 |\n",
        "| STS-B | 1 / 16 / 2e-5 / 5  |  1 / 16 / 4e-5 / 12 |  4 / 16 / 3e-5 / 12 |\n",
        "| QQP   | 1 / 16 / 2e-5 / 5  | 4 / 16 / 1e-5 / 12  |  4 / 16 / 1e-5 / 12 |\n",
        "| MNLI  | 4 / 64 / 1e-5 / 5  |  4 / 32 / 1e-5 / 5  |  4 / 32 / 1e-5 / 5  | \n",
        "| QNLI  | 4 / 16 / 1e-5 / 5  |  4 / 16 / 1e-5 / 5  |  4 / 16 / 2e-5 / 5  | \n",
        "| RTE   | 1 / 16 / 1e-5 / 5  | 1 / 16 / 1e-5 / 12  |  4 / 16 / 3e-5 / 12 |\n"
      ]
    }
  ]
}